package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.dto.pyq.FeedMedia;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.RegularUtil;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.pyq.pyqmaterial.PyqMaterialDto;
import com.uzai.console.dto.pyq.pyqmaterial.PyqMaterialIdDto;
import com.uzai.console.dto.pyq.pyqmaterial.PyqMaterialQuery;
import com.uzai.console.dto.pyq.pyqmaterial.TurnlinkDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.service.pyq.PyqMaterialService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import com.uzai.console.vo.pyq.pyqmaterial.PyqMaterialVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 朋友圈素材
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqMaterialServiceImpl implements PyqMaterialService {

    Logger logger = LoggerFactory.getLogger(PyqMaterialServiceImpl.class);

    @Autowired
    private PyqMaterialMapper pyqMaterialMapper;
    @Autowired
    private PyqCommentTemplateMapper pyqCommentTemplateMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 查询朋友圈素材列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqMaterialQuery
     * @return null
     */
    public Page<PyqMaterialVo> findPyqMaterialList(PyqMaterialQuery pyqMaterialQuery){
        //新建返回到页面的LIST对象
        List<PyqMaterialVo> pyqMaterialPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<PyqMaterial> page = new Page<>();
        pyqMaterialQuery.convert(page);
        ArrayList<PyqMaterial> pyqMaterialList =  pyqMaterialMapper.findByList(page, pyqMaterialQuery);
        if(pyqMaterialList != null && pyqMaterialList.size() > 0){
            for (PyqMaterial pyqMaterial : pyqMaterialList){
                PyqMaterialVo pyqMaterialPageVo = new PyqMaterialVo();
                BeanUtils.copyProperties(pyqMaterial, pyqMaterialPageVo);

                //封装图片
                if(StringUtils.isNotBlank(pyqMaterial.getFeedMedia())){
                    List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqMaterial.getFeedMedia(), FeedMedia.class);
                    if(feedMediaList != null && feedMediaList.size() > 0){
                        List<String> imgList = new ArrayList<>();
                        if(Tools.getInteger(pyqMaterial.getAttachType()).intValue() == 2){
                            for (FeedMedia feedMedia : feedMediaList) {
                                imgList.add(feedMedia.getUrl());
                            }
                        }else{
                            for (FeedMedia feedMedia : feedMediaList) {
                                imgList.add(feedMedia.getCover());
                            }
                        }
                        pyqMaterialPageVo.setImgList(imgList);
                    }
                }else{ //旧版接口
                    if(StringUtils.isNotBlank(pyqMaterial.getImgs())){
                        List<String> imgList = JSONObject.parseArray(pyqMaterial.getImgs(), String.class);
                        pyqMaterialPageVo.setImgList(imgList);
                    }
                }

                pyqMaterialPageVoList.add(pyqMaterialPageVo);
            }
        }
        //返回到页面分页对象
        Page<PyqMaterialVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(pyqMaterialPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询朋友圈素材详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqMaterialIdDto
     * @return null
     */
    public PyqMaterialVo findPyqMaterial(PyqMaterialIdDto pyqMaterialIdDto){
        if(pyqMaterialIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        PyqMaterial pyqMaterial = pyqMaterialMapper.selectById(pyqMaterialIdDto.getId(), pyqMaterialIdDto.getMerId());

        if(pyqMaterial == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该朋友圈素材不存在");
        }

        PyqMaterialVo pyqMaterialVo = new PyqMaterialVo();
        BeanUtils.copyProperties(pyqMaterial, pyqMaterialVo);

        //封装图片
        if(StringUtils.isNotBlank(pyqMaterial.getFeedMedia())){
            List<FeedMedia> feedMediaList = JSONObject.parseArray(pyqMaterial.getFeedMedia(), FeedMedia.class);
            if(feedMediaList != null && feedMediaList.size() > 0){
                List<String> imgList = new ArrayList<>();
                if(Tools.getInteger(pyqMaterial.getAttachType()).intValue() == 2){
                    for (FeedMedia feedMedia : feedMediaList) {
                        imgList.add(feedMedia.getUrl());
                    }
                }else{
                    for (FeedMedia feedMedia : feedMediaList) {
                        imgList.add(feedMedia.getCover());
                    }
                }
                pyqMaterialVo.setImgList(imgList);
            }
        }else{ //旧版接口
            if(StringUtils.isNotBlank(pyqMaterial.getImgs())){
                List<String> imgList = JSONObject.parseArray(pyqMaterial.getImgs(), String.class);
                pyqMaterialVo.setImgList(imgList);
            }
        }

        return pyqMaterialVo;
    }

    /**
     * 添加朋友圈素材
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqMaterialDto
     * @return null
     */
    public void addPyqMaterial(PyqMaterialDto pyqMaterialDto){

        if(pyqMaterialDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        if(pyqMaterialDto.getType() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择类型");
        }

        //商品，额外增加判断
        if(pyqMaterialDto.getType().intValue() == 0){
            if(pyqMaterialDto.getPlatform() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择平台");
            }

            if(StringUtils.isBlank(pyqMaterialDto.getItemId())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入商品链接/id");
            }
        }else{
            pyqMaterialDto.setPlatform(20); //图文默认平台=20
        }

        if(pyqMaterialDto.getAttachType().intValue() == 5){
            if(StringUtils.isBlank(pyqMaterialDto.getFeedMedia())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "视频号附件不能为空");
            }

            if(StringUtils.isBlank(pyqMaterialDto.getVideoNumber())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "视频号参数不能为空");
            }
        }

        Integer now = DateUtil.getNowTime();
        PyqMaterial pyqMaterial = new PyqMaterial();
        pyqMaterial.setId(IdWorker.getId());
        pyqMaterial.setMerId(pyqMaterialDto.getMerId());
        pyqMaterial.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
        pyqMaterial.setType(pyqMaterialDto.getType());
        pyqMaterial.setPlatform(pyqMaterialDto.getPlatform());
        pyqMaterial.setDevicePlanId(pyqMaterialDto.getDevicePlanId());
        pyqMaterial.setItemId(pyqMaterialDto.getItemId());
        pyqMaterial.setCouponId(pyqMaterialDto.getCouponId());
        pyqMaterial.setCouponVal(pyqMaterialDto.getCouponVal());
        pyqMaterial.setFinalPrice(pyqMaterialDto.getFinalPrice());
        pyqMaterial.setContentId(pyqMaterialDto.getContentId());
        pyqMaterial.setContent(pyqMaterialDto.getContent());

        //封装附件类型
        int attachType = pyqMaterialDto.getAttachType(); //默认图文

        if(attachType == 2){//只发图文
            //封装附件对象
            List<FeedMedia> feedMediaList = new ArrayList<>();
            //图片
            List<String> imgList = pyqMaterialDto.getImgList();
            if(imgList != null && imgList.size() > 9){
                imgList = imgList.subList(0, 9);
            }
            if(imgList != null && imgList.size() > 0){
                for (String item : imgList){
                    if(StringUtils.isNotBlank(item)){
                        FeedMedia feedMedia = new FeedMedia();
                        feedMedia.setMediaType(2);
                        feedMedia.setUrl(item);
                        feedMediaList.add(feedMedia);
                    }
                }
            }
            pyqMaterial.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        }else{ //发送视频
            pyqMaterial.setFeedMedia(pyqMaterialDto.getFeedMedia());
        }

        //新版朋友圈接口新增加字段
        pyqMaterial.setAttachType(attachType);
        pyqMaterial.setVideoNumber(Tools.getStrNull(pyqMaterialDto.getVideoNumber()));
        pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西
        pyqMaterial.setCommentId(pyqMaterialDto.getCommentId());
        pyqMaterial.setCommentContent(pyqMaterialDto.getCommentContent());
        pyqMaterial.setCreateTime(now);
        pyqMaterial.setUpdateTime(now);
        pyqMaterialMapper.insert(pyqMaterial);
    }

    /**
     * 修改朋友圈素材
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqMaterialDto
     * @return null
     */
    public void updatePyqMaterial(PyqMaterialDto pyqMaterialDto){
        if(pyqMaterialDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(pyqMaterialDto.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        if(pyqMaterialDto.getType() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择类型");
        }

        //商品，额外增加判断
        if(pyqMaterialDto.getType().intValue() == 0){
            if(pyqMaterialDto.getPlatform() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择平台");
            }

            if(StringUtils.isBlank(pyqMaterialDto.getItemId())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入商品链接/id");
            }
        }else{
            pyqMaterialDto.setPlatform(20); //图文默认平台=20
        }

        if(pyqMaterialDto.getAttachType().intValue() == 5){
            if(StringUtils.isBlank(pyqMaterialDto.getFeedMedia())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "视频号附件不能为空");
            }

            if(StringUtils.isBlank(pyqMaterialDto.getVideoNumber())){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "视频号参数不能为空");
            }
        }

        PyqMaterial pyqMaterial = pyqMaterialMapper.selectById(pyqMaterialDto.getId(), pyqMaterialDto.getMerId());
        if(pyqMaterial == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材不存在");
        }
        pyqMaterial.setMerId(pyqMaterialDto.getMerId());
        pyqMaterial.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
        pyqMaterial.setType(pyqMaterialDto.getType());
        pyqMaterial.setPlatform(pyqMaterialDto.getPlatform());
        pyqMaterial.setDevicePlanId(pyqMaterialDto.getDevicePlanId());
        pyqMaterial.setItemId(pyqMaterialDto.getItemId());
        pyqMaterial.setCouponId(pyqMaterialDto.getCouponId());
        pyqMaterial.setCouponVal(pyqMaterialDto.getCouponVal());
        pyqMaterial.setFinalPrice(pyqMaterialDto.getFinalPrice());
        pyqMaterial.setContentId(pyqMaterialDto.getContentId());
        pyqMaterial.setContent(pyqMaterialDto.getContent());

        //封装附件类型
        int attachType = pyqMaterialDto.getAttachType(); //默认图文
        if(attachType == 2){//只发图文
            //封装附件对象
            List<FeedMedia> feedMediaList = new ArrayList<>();
            //图片
            List<String> imgList = pyqMaterialDto.getImgList();
            if(imgList != null && imgList.size() > 9){
                imgList = imgList.subList(0, 9);
            }
            if(imgList != null && imgList.size() > 0){
                for (String item : imgList){
                    if(StringUtils.isNotBlank(item)){
                        FeedMedia feedMedia = new FeedMedia();
                        feedMedia.setMediaType(2);
                        feedMedia.setUrl(item);
                        feedMediaList.add(feedMedia);
                    }
                }
            }
            pyqMaterial.setFeedMedia(Tools.getStrNull(JSONObject.toJSONString(feedMediaList)));
        }else{ //发送视频
            pyqMaterial.setFeedMedia(pyqMaterialDto.getFeedMedia());
        }
        //新版朋友圈接口新增加字段
        pyqMaterial.setAttachType(attachType);
        pyqMaterial.setVideoNumber(Tools.getStrNull(pyqMaterialDto.getVideoNumber()));
        pyqMaterial.setImgs(null);  //新版朋友圈接口，img不存放任何东西

        pyqMaterial.setCommentId(pyqMaterialDto.getCommentId());
        pyqMaterial.setCommentContent(pyqMaterialDto.getCommentContent());
        Integer now = DateUtil.getNowTime();
        pyqMaterial.setUpdateTime(now);
        pyqMaterialMapper.updateById(pyqMaterial);
    }

    /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqMaterialIdDto
     * @return null
     */
    public void deletePyqMaterial(PyqMaterialIdDto pyqMaterialIdDto){
        if(pyqMaterialIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        pyqMaterialMapper.deleteById(pyqMaterialIdDto.getId(), pyqMaterialIdDto.getMerId());
    }

    /**
     * 获取商品信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param turnlinkDto
     * @return null
     */
    public SimpleTurnlinkVo getGoodInfo(TurnlinkDto turnlinkDto){
        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();
        if(turnlinkDto.getPlatform() == null){
            logger.info("请选择平台");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择平台");
        }

        if(turnlinkDto.getDevicePlanId() == null){
            logger.info("请选择设备方案");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(turnlinkDto.getDevicePlanId(), turnlinkDto.getMerId());

        if(pyqDevicePlan == null){
            logger.info("该设备方案不存在");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该设备方案不存在");
        }

        Long deviceUniqueId = turnlinkDto.getDeviceUniqueId();
        Long tbTokenId = null;
        String pid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Long dyTokenId = null;
        Long ksTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;
        Integer ksTokenType = null;
        Integer jdTokenType = null;
        Integer vphTokenType = null;

        //默认机器人为空，则未指定，则指定配置方案中的默认第一个机器人
        if(deviceUniqueId == null){
            //发送朋友圈的机器人列表
            List<Long> deviceUniqueIdList = null;
            if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
                //验证发送机器人
                deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
            }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
                DeviceQuery deviceQuery = new DeviceQuery();
                deviceQuery.setMerId(turnlinkDto.getMerId());
                deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
                Page<Device> page = deviceService.findDevicePage(deviceQuery);
                if(page != null && page.getRecords() != null && page.getRecords().size() > 0){
                    deviceUniqueIdList = new ArrayList<>();
                    for (Device device : page.getRecords()){
                        deviceUniqueIdList.add(device.getId());
                    }
                }
            }
            if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
                logger.info("该设备方案未选择机器人");
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该设备方案未选择机器人");
            }
            deviceUniqueId = deviceUniqueIdList.get(0);
        }

        //查询机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, pyqDevicePlan.getDeviceType(), turnlinkDto.getMerId());
        if(device == null ){
            logger.info("请求商品转链-机器人id为空");
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人id为空");
        }

        if(pyqDevicePlan.getTokenType() != null && pyqDevicePlan.getTokenType().intValue() == 1){ //自己设置联盟
            JSONObject jsonObjectToken = JSONObject.parseObject(pyqDevicePlan.getTokenInfo());
            if(jsonObjectToken != null){
                //淘宝token
                JSONObject tbTokenJsonObject  = jsonObjectToken.getJSONObject("tbToken");
                if(tbTokenJsonObject != null){
                    tbTokenId = tbTokenJsonObject.getLong("tokenId");
                    pid = tbTokenJsonObject.getString("pid");
                }
                //京东token
                JSONObject jdTokenJsonObject  = jsonObjectToken.getJSONObject("jdToken");
                if(jdTokenJsonObject != null){
                    jdTokenId = jdTokenJsonObject.getLong("tokenId");
                    jdTokenType = jdTokenJsonObject.getInteger("type");
                }
                //拼多多token
                JSONObject pddTokenJsonObject  = jsonObjectToken.getJSONObject("pddToken");
                if(pddTokenJsonObject != null){
                    pddTokenId = pddTokenJsonObject.getLong("tokenId");
                    pddTokenType = pddTokenJsonObject.getInteger("type");
                }
                //唯品会token
                JSONObject vphTokenJsonObject  = jsonObjectToken.getJSONObject("vphToken");
                if(vphTokenJsonObject != null){
                    vphTokenId = vphTokenJsonObject.getLong("tokenId");
                    vphTokenType = vphTokenJsonObject.getInteger("type");
                }
                //抖音token
                JSONObject dyTokenJsonObject  = jsonObjectToken.getJSONObject("dyToken");
                if(dyTokenJsonObject != null){
                    dyTokenId = dyTokenJsonObject.getLong("tokenId");
                    dyTokenType = dyTokenJsonObject.getInteger("type");
                }
                //快手token
                JSONObject ksTokenJsonObject  = jsonObjectToken.getJSONObject("ksToken");
                if(ksTokenJsonObject != null){
                    ksTokenId = ksTokenJsonObject.getLong("tokenId");
                    ksTokenType = ksTokenJsonObject.getInteger("type");
                }
            }
        }else{ //默认从机器人中获取
            ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
            if(configPlan != null){
                //淘宝token-淘宝目前不从配置方案中获取,淘宝商品转链采用导购联盟
                if(false){
                    JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                    if(jsonObject_tb != null) {
                        JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                tbTokenId = tokenList.get(0);
                                TbToken tbToken = tbTokenMapper.selectById(tbTokenId, turnlinkDto.getMerId());
                                if (tbToken != null) {
                                    pid = tbToken.getDefPid();
                                }
                            }
                        }
                    }
                }

                //京东token
                JSONObject jsonObject_jd = null;
                jdTokenType = configPlan.getJdAccountType();
                if(jdTokenType != null && jdTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getTlbJdAccountId());
                }else{ //拼多多联盟
                    jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                }
                if(jsonObject_jd != null) {
                    JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            jdTokenId = tokenList.get(0);
                        }
                    }
                }

                //唯品会token
                JSONObject jsonObject_vph = null;
                vphTokenType = configPlan.getVphAccountType();
                if(vphTokenType != null && vphTokenType.intValue() == 1){ //推老板共享联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getTlbVphAccountId());
                }else{ //拼多多联盟
                    jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                }
                if(jsonObject_vph != null) {
                    JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            vphTokenId = tokenList.get(0);
                        }
                    }
                }

                //拼多多token
                JSONObject jsonObject_pdd = null;
                pddTokenType = configPlan.getPddAccountType();
                if(configPlan.getPddAccountType() != null && configPlan.getPddAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                }else{ //拼多多联盟
                    jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                }
                if(jsonObject_pdd != null) {
                    JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            pddTokenId = tokenList.get(0);
                        }
                    }
                }

                //抖音token
                JSONObject jsonObject_dy = null;
                dyTokenType = configPlan.getDyAccountType();
                if(configPlan.getDyAccountType() != null && configPlan.getDyAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                }else{ //拼多多联盟
                    jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                }
                if(jsonObject_dy != null) {
                    JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            dyTokenId = tokenList.get(0);
                        }
                    }
                }

                //快手token
                JSONObject jsonObject_ks = null;
                ksTokenType = configPlan.getKsAccountType();
                if(configPlan.getKsAccountType() != null && configPlan.getKsAccountType().intValue() == 1){ //推老板共享联盟
                    jsonObject_ks = JSONObject.parseObject(configPlan.getTlbKsAccountId());
                }else{ //快手联盟
                    jsonObject_ks = JSONObject.parseObject(configPlan.getKsAccountId());
                }
                if(jsonObject_ks != null) {
                    JSONArray jsonArray = jsonObject_ks.getJSONArray("tokens");
                    if (jsonArray != null && jsonArray.size() > 0) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                        String tokenIds = jsonObject.getString("tokenIds");
                        List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                        if (tokenList != null && tokenList.size() > 0) {
                            ksTokenId = tokenList.get(0);
                        }
                    }
                }
            }
        }

        if(StringUtils.isBlank(turnlinkDto.getItemId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品链接/id/淘口令/抖音口令");
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new  SimpleTurnLinkDto();
        if(StringUtils.isNotBlank(turnlinkDto.getUrl())){
            simpleTurnLinkDto.setUrl(turnlinkDto.getUrl());
        }
        simpleTurnLinkDto.setMerId(turnlinkDto.getMerId());
        simpleTurnLinkDto.setDeviceUniqueId(deviceUniqueId);
        simpleTurnLinkDto.setDeviceType(device.getRecvmsgType());
        simpleTurnLinkDto.setCouponId(turnlinkDto.getCouponId());
        simpleTurnLinkDto.setBizSceneId(turnlinkDto.getBizSceneId());
        simpleTurnLinkDto.setGenerateShortUrl(turnlinkDto.getGenerateShortUrl());
        simpleTurnLinkDto.setMiddlePageDomainId(pyqDevicePlan.getDomain());
        simpleTurnLinkDto.setIgnoreShortUrlAuth(turnlinkDto.getIgnoreShortUrlAuth());
        simpleTurnLinkDto.setChannel(OrderSourceEnum.WECHAT_PYQ.getId());//个人微信朋友圈

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if(PlatformTypeEnum.PT_TAOBAO.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //淘宝
            if(tbTokenId == null) { //设备方案未配置淘宝联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置淘宝联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置淘宝联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置淘宝联盟");

            }else{
                int tbQueryType = RegularUtil.getTbQueryType(turnlinkDto.getItemId());
                if(tbQueryType == 1){
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else if(tbQueryType == 2){
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }else if(tbQueryType == 3){
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId());
                }else{
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未识别到商品信息");
                }
                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(pid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用淘宝转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_JD.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //京东

            if(jdTokenId == null){ //发单设备方案未配置京东联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置京东联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置京东联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置京东联盟");

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }
                simpleTurnLinkDto.setTokenId(jdTokenId);
                simpleTurnLinkDto.setJdTokenType(jdTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_PDD.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //拼多多
            if(pddTokenId == null){ //发单设备方案未配置拼多多联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置拼多多联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置拼多多联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置拼多多联盟");

            }else{
                //拼多多商品优先选择商品url进行转链。（商品id进行转链不能参加千万补贴）
                if(StringUtils.isNotBlank(turnlinkDto.getUrl())){
                    simpleTurnLinkDto.setUrl(turnlinkDto.getUrl());
                }else{
                    if(turnlinkDto.getItemId().contains("http")){//商品链接
                        simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                    }else{
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }
                }

                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(PlatformTypeEnum.PT_VPH.getId().intValue() == turnlinkDto.getPlatform().intValue()){ //唯品会
            if(vphTokenId == null){ //发单设备方案未配置唯品会联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "",0L,
                        "朋友圈-设备方案未配置唯品会联盟")));

                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置唯品会联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setUrl(turnlinkDto.getItemId());
                }else{
                    simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                }
                simpleTurnLinkDto.setTokenId(vphTokenId);
                simpleTurnLinkDto.setVphTokenType(vphTokenType);
                uzaiRespVo =uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(turnlinkDto.getPlatform().intValue() == 4){//抖音
            if(dyTokenId == null) { //设备方案未配置淘宝联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置抖音联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置抖音联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);


                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置抖音联盟");

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId()); //抖音连接转链参数放pwd参数
                }else{
                    //先判断商品id
                    String itemId = Tools.findTbItemIdByRegex(turnlinkDto.getItemId());
                    if(StringUtils.isNotBlank(itemId)){
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }else{
                        //查找淘口令，找到通过淘口令转链
                        String pwd = Tools.findTbPwdByRegex(turnlinkDto.getItemId());
                        if(StringUtils.isNotBlank(pwd)){
                            simpleTurnLinkDto.setPwd(pwd);
                        }else{ //最后则默认为商品id
                            simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                        }
                    }
                }

                simpleTurnLinkDto.setTokenId(dyTokenId);
                simpleTurnLinkDto.setDyTokenType(dyTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.dyTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用抖音转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }else if(turnlinkDto.getPlatform().intValue() == 5){//快手
            if(ksTokenId == null) { //设备方案未配置快手联盟id
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                        pyqDevicePlan.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "朋友圈-设备方案未配置快手联盟")));
                //系统设置错误
                AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
                alarmMsgFeignDto.setMerId(device.getMerId());
                alarmMsgFeignDto.setType(SysMsgTypeEnum.SYS_SET_ERR.getValue()); //系统设置错误
                alarmMsgFeignDto.setDeviceUniqueId(null);
                alarmMsgFeignDto.setDeviceType(null);
                //消息
                JSONObject ext = new JSONObject();
                ext.put("content", "朋友圈-设备方案未配置快手联盟");
                alarmMsgFeignDto.setExt(ext.toJSONString());
//                UzaiRespVo uzaiRespVo_alarm = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//                logger.info("---发送系统设置错误报警--para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo_alarm));

                //2024-01-09修改成直接发送MQ
                noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置快手联盟");

            }else{
                //判断输入得是商品id还是商品链接
                if(turnlinkDto.getItemId().contains("http")){//商品链接
                    simpleTurnLinkDto.setPwd(turnlinkDto.getItemId()); //快手连接转链参数放pwd参数
                }else{
                    //判断输入得是商品id还是商品链接
                    if(Tools.isInteger(turnlinkDto.getItemId())){
                        simpleTurnLinkDto.setItemId(turnlinkDto.getItemId());
                    }else{
                        simpleTurnLinkDto.setPwd(turnlinkDto.getItemId());
                    }
                }

                simpleTurnLinkDto.setTokenId(ksTokenId);
                simpleTurnLinkDto.setKsTokenType(ksTokenType);
                uzaiRespVo = uzaiTurnlinkFeignService.ksTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用快手转链- 参数={}，返回结果={}",JSONObject.toJSONString(simpleTurnLinkDto),JSONObject.toJSONString(uzaiRespVo));
            }
        }

        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
            simpleTurnlinkVo = uzaiRespVo.getData();
        }else{
            logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_PYQ_SEND_HANDER_VALUE,
                    turnlinkDto.getMerId(), device.getRecvmsgType(), deviceUniqueId,
                    "",0L,
                    "转链失败；"+uzaiRespVo.getMsg())));

            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }

        return simpleTurnlinkVo;
    }

}
